# coding:utf8
'''
    购物车相关
'''
from flask_restful import Resource, request
from _sys.parser import parsers
from _sys.models import MongodbOperations, ResponseJson, Token, CreateId, FormatIO
from _sys.code import dbNameDict
from _sys.function import allow_cross, admin_open_ips, had_power,format_words, parse_param_info

import time

mgOp = MongodbOperations()
responseJson = ResponseJson()
token = Token()
cId = CreateId()

class Cart(Resource):
    '''
        /cart
        购物车
        -- get 获取购物车 -- user使用
        -- post 修改购物车相关
        -- put 添加商品进入购物车
        -- delete 删除购物车商品
    '''
    @allow_cross
    def get(self):
        args = parsers()
        u_id = args.get('u_id')
        u_token = args.get('u_token')
        if token.verify(u_token, u_id):   # 权限正确
            cart_data = mgOp.find_many(dbNameDict['userCartData'], filter={'u_id':u_id})
            rd = []
            for p in cart_data:
                d = mgOp.find_one(dbNameDict['productData'], filter={'p_id': p['p_id']})  # 对应商品信息
                temp = {    # 报文模板
                    'p_id': d['p_id'],
                    'p_name': d['p_name'],
                    'p_title':d['p_title'],
                    'p_brand':d['p_brand'],
                    'p_color': d['p_color'],
                    'p_sub_title': d['p_sub_title'],
                    'p_size': p['p_size'],
                    'p_pic':d['p_img'],
                    'p_count':p['p_count'],
                    'p_price':d['p_price']
                }
                rd.append(temp)
            return responseJson.correct(code='ok', data=rd)
        else:
            return responseJson.error_response(code='tokenFailure')

    @allow_cross
    def post(self):
        '''
            修改购物车产品内容  会员
            更改商品数量 或者 删除该商品
        :return:
        '''
        args = parsers()
        u_id = args.get('u_id')
        u_token = args.get('u_token')
        p_id = args.get('p_id')
        p_count = args.get('num')
        p_size = args.get('p_size')

        try:
            p_count = int(p_count)
        except Exception:
            return responseJson.error_response(code='lackOfNecessaryParameters')

        if token.verify(u_token,u_id):
            if p_count == 0:  #商品被删除
                if mgOp.delete_one(dbNameDict['userCartData'], filter={'u_id':u_id ,'p_id':p_id, 'p_size':p_size}):
                    return responseJson.correct(code='ok', data={'msg':'删除商品成功'})
                else:
                    return responseJson.error_response(code='resourcesDoNotExist')
            elif p_count > 0:
                nd = {'p_count': p_count}
                if mgOp.update_one(dbNameDict['userCartData'], filter={'u_id':u_id ,'p_id':p_id, 'p_size':p_size}, data=nd):
                    return responseJson.correct(code='ok', data={'msg':'修改商品数量成功'})
                else:
                    return responseJson.error_response(code='resourcesDoNotExist')
            else:
                return responseJson.error_response(code='lackOfNecessaryParameters')  # 参数错误
        else:
            return responseJson.error_response(code='tokenFailure')   # token失效

    @allow_cross
    def put(self):
        args = parsers()
        u_id = args.get('u_id')
        u_token = args.get('u_token')
        p_id = args.get('p_id')
        p_count = args.get('num')
        p_size = args.get('p_size')
        if token.verify(u_token, u_id):
            p_data = mgOp.find_one(dbNameDict['productData'], filter={'p_id':p_id})   # 查询产品信息
            if p_data and p_count and p_size:
                rd = mgOp.find_one(dbNameDict['userCartData'], filter={'p_id':p_id, 'u_id':u_id, 'p_size':p_size})
                if rd:  # 已添加过该产品
                    try:
                        p_count = int(rd['p_count']) + int(p_count)
                    except Exception:
                        return responseJson.error_response(code='lackOfNecessaryParameters')  # 参数错误
                    d = {
                        'p_count': str(p_count),
                    }
                    if mgOp.update_one(dbNameDict['userCartData'], filter={'p_id': p_id, 'u_id': u_id}, data=d):  # 增加数量
                        count = len(mgOp.find_many(dbNameDict['userCartData'], filter={'u_id': u_id}))
                        return responseJson.correct(code='ok', data={'msg':'添加商品成功', 'len': count})
                else:   # 新添加
                    d = {   # 构建购物车数据
                        'p_id': p_id,
                        'p_count': p_count,
                        'p_size':p_size,
                        'u_id': u_id,
                        'create_time': str(time.time()),
                        'format_time':FormatIO().timestamp_format(time.time())
                    }
                    if mgOp.insert_one(dbNameDict['userCartData'],d):    # 插入数据
                        count = len(mgOp.find_many(dbNameDict['userCartData'], filter={'u_id': u_id}))
                        return responseJson.correct(code='ok', data={'msg': '添加商品成功', 'len': count})
                    else:
                        return responseJson.error_response(code='unknownError')
            else:
                return responseJson.error_response(code='resourcesDoNotExist')   # 不存在产品
        else:  # 权限验证失败
            return responseJson.error_response(code='tokenFailure')

    @allow_cross
    def delete(self):
        '''
            删除购物车产品
        :return:
        '''
        args = parsers()
        u_id = args.get('u_id')
        u_token = args.get('u_token')
        p_id = args.get('p_id')
        p_size = args.get('p_size')

        if token.verify(u_token, u_id):
            try:
                mgOp.delete_one(dbNameDict['userCartData'], filter={'u_id':u_id, 'p_id':p_id, 'p_size':p_size})
                return responseJson.correct(code='ok', data={'msg':'删除购物车商品成功'})
            except Exception:
                return responseJson.error_response(code='unknownError')
        else:
            return responseJson.error_response(code='tokenFailure')


